import React from "react";
import {Popover, Select, Tooltip} from "antd";
import BaseComponent from "../../../redare/components/BaseComponent";
import {ifTrue, isEmpty} from "../../../redare/utils/Utils";
import {strToNum} from "../../../common/Utils";

/**
 * 用于自定义下拉，相当于DictSelect 可更换数据源
 * @date 2020-7-9 14:38:02
 * @author WanJie.Peng
 */
export default class DataSelect extends BaseComponent {

  static defaultProps = {
    data:[],
    matchkey: undefined,
    matchname: '',
    popupcontainer: undefined,
    parsreint: "false", // key 是否要转换成数值
  };

  //popover 内容渲染函数
  popoverContentFn = undefined;

  // 数据转成Map
  dataMap={};

  constructor(props) {
    super(props);
    let changeValue = undefined;
    if( this.props.value ){
      changeValue = this.props.value;
    }
    this.state = {
      dArray: [],
      loading: true,
      changeValue: changeValue
    };
  }

  componentDidMount() {
    if( this.props.data && this.props.data.constructor === Array && this.props.data.length > 0){
      this.setState({dArray: this.props.data,loading: false });
    }
  }

  setValue(value){
    this.setState({changeValue:value})
  }

  // 设置请求源数据加载 Presenter 之后的回调
  setRequestData(requestPromiseFn) {
    if (!requestPromiseFn) {
      return;
    }
    this.setState({loading: true, dArray: []});
    requestPromiseFn().then((data) => {
      let array = [];
      if (!data || data.constructor === Array) {
        array = data;
      }
      this.setState({dArray: array, loading: false});
    }).catch(() => {
      this.setState({loading: false});
    });
  }
  // 设置源数据
  setSourceData(data){
    this.setState({dArray: [...data], loading: false });
  }

  getSourceData(){
    return this.state.dArray;
  }

  setSourceLoading(){
    this.setState({loading: true});
    setTimeout(()=>{
      this.setState({loading: false});
    }, 3000);
  }


  // 赋值
  setData(data){
    this.setState({changeValue: data});
  }
  // 获取值
  getData(){
    let changeValue = this.state.changeValue;
    return !isEmpty(changeValue) ? changeValue : this.props.value;
  }

  _onchange = (value, option)=>{
    this.select.focus();
    this.setState({changeValue: value});
    let changeFn = this.props.onChange;
    if( changeFn && changeFn.constructor === Function ){
      changeFn(value, option);
    }
  }

  render() {

    let dArray = this.state.dArray || [];
    let match_key = this.props.matchkey || 'id';
    let match_name = this.props.matchname || 'name';
    // 拼接显示
    let matchNameArray = this.props.matchnamearray || undefined;
    let matchNameSymbol = this.props.matchnamesymbol || ' - ';

    let attr = {...this.props};
    if (!attr.placeholder) {
      attr.placeholder = '请选择';
    }

    let value = this.state.changeValue;
    if( isEmpty(value) && this.props.value && !this.state.loading ){
      value = this.props.value;
    }

    if( ifTrue(value) && ( this.props.parsreint === true || this.props.parsreint === "true" ) ){
      if( value.constructor === Array ){
        value.forEach((item,index)=>{
          value[index] = strToNum(item);
        });
      }else {
        value = strToNum( value );
      }
    }


    // 提示
    let hint = (item, _name)=>{
      if( this.popoverContentFn && typeof this.popoverContentFn === 'function'){
        return (
          <Popover placement="rightTop" title={_name} content={this.popoverContentFn(item)} trigger="hover">
            <div>{_name}</div>
          </Popover>
        );
      }else {
        return <Tooltip title={_name}><div>{_name}</div></Tooltip>
      }
    };

    let popupContainer = this.props.popupcontainer;



    return (


      <Select
        ref={(the)=>{this.select = the }}
        allowClear={true}
        style={{width: '100%'}}
        showSearch={true}
        loading={this.state.loading}
        optionFilterProp="children"
        {...attr}
        value={value}
        onChange={this._onchange}
        getPopupContainer={(triggerNode)=>{
          if( popupContainer ){
            return popupContainer;
          }else {
            return triggerNode.parentElement;
          }
        }}
        filterOption={(inputValue,option)=>{
          if( option.data[match_name].indexOf(inputValue) > -1 ){
            return true;
          }
          return false;
        }}
      >
        {
          dArray.map((item) => {
            let _name = item[match_name];
            if (matchNameArray && matchNameArray.length > 0) {
              _name = '';
              for (let i = 0; i < matchNameArray.length; i++) {
                if (i == 0) {
                  _name = item[matchNameArray[i]];
                } else {
                  _name = _name + matchNameSymbol + item[matchNameArray[i]];
                }
              }
            }


            return (
              <Select.Option key={"option_" + item[match_key]} value={item[match_key]} data={item}>
                {hint(item, _name)}
              </Select.Option>
            )
          })
        }
      </Select>
    );
  }

}